﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using System.Reflection;

namespace Magic.Core;

public static class DependencyInjectionServiceCollectionExtensions
{
    /// <summary>
    /// 添加依赖注入接口
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddDependencyInjection(this IServiceCollection services)
    {
        var types = DependencyContext.Default?.RuntimeLibraries.Where(o => o.Name.StartsWith("Magic.")).Select(o => Assembly.Load(new AssemblyName(o.Name))).SelectMany(m => m.GetTypes())
            .Where(m =>
                           m.GetCustomAttributes(typeof(InjectionAttribute), false).Any()
                           && m.IsClass
                           && !m.IsAbstract)
            .ToList() ?? new List<Type>();

        foreach (var type in types)
        {
            {
                Type[] interfaces = type.GetInterfaces();
                var lifeTime = type.GetCustomAttribute<InjectionAttribute>()?.LifeTime;
                foreach (var iface in interfaces)
                {
                    _ = lifeTime switch
                    {
                        ServiceLifeTime.Singleton => services.AddSingleton(iface, type),
                        ServiceLifeTime.Scoped => services.AddScoped(iface, type),
                        ServiceLifeTime.Transient => services.AddTransient(iface, type),
                        _ => services.AddTransient(iface, type)

                    };
                }
            }
        }
        return services;
    }
}
